package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.service.IBasicMaterialsBomService;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicProductionGetDO;
import com.cssy.xxkj.logic.entity.LogicProductionGetItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionReturnDO;
import com.cssy.xxkj.logic.entity.LogicProductionReturnItemDO;
import com.cssy.xxkj.logic.service.ILogicProductionGetService;
import com.cssy.xxkj.logic.service.ILogicProductionReturnService;
import com.cssy.yd.logic.util.MathUtil;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;
/**
 * 生产退料控制器
 * @author hf
 *
 */
@Controller
@RequestMapping("/logic/proreturn")
public class ProductionReturnController extends BaseController<LogicProductionReturnDO> {
	
	private static final Logger logger = Logger.getLogger(ProductionReturnController.class);

	private static final String MANAGER = "/xxkj/logic/productionreturn/ProReturnManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/productionreturn/ProReturnOperation";// 添加、修改、显示页面

	@Resource(name = "logicProductionReturnService")
	private ILogicProductionReturnService logicProductionReturnService;
	
	@Resource(name = "logicProductionGetService")
	private ILogicProductionGetService logicProductionGetService;
	
	@Resource(name="basicMaterialsBomService")
	private IBasicMaterialsBomService basicMaterialsBomService;
	//主数据公用集合Service
	@Resource(name="basicUtilService")
	private IBasicUtilService basicUtilService;

	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs.setOrderBy("bizCreatorDate desc");
		SearchResult result = logicProductionReturnService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			model.addAttribute("viewflag", "add");
			model.addAttribute("xx", 1);//标示能不能修改内容
		}else{
			LogicProductionReturnDO oi = logicProductionReturnService.findListById(id);
			model.addAttribute("oi", oi);
			if (oi.getZd011BillStatus().equals(BillStatusUtil.PRORETURN_STATUS_ONE)||oi.getZd011BillStatus().equals(BillStatusUtil.PRORETURN_STATUS_SIX)){
				model.addAttribute("xx", 1);//标示能不能修改内容
				model.addAttribute("viewflag", "tijiao");
			}else {
				model.addAttribute("xx", 2);//标示能不能修改内容
			}
			if (oi.getZd011BillStatus().equals(BillStatusUtil.PRORETURN_STATUS_FIVE)){
				model.addAttribute("viewflag", "tongguo");
			}
			if (oi.getZd011BillStatus().equals(BillStatusUtil.PRORETURN_STATUS_THREE)){
				model.addAttribute("viewflag", "shenpi");
			}
		}
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicProductionReturnDO prodispat = logicProductionReturnService.findListById(id);
			List<LogicProductionReturnItemDO> soitem = logicProductionReturnService.findReturnItemList(prodispat.getId());
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicProductionReturnDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("addressInfos");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			logicProductionReturnService.returnSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicProductionReturnDO ld = logicProductionReturnService.findListById(field);
				logicProductionReturnService.deleteBizRemoved(ld.getId());
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	@RequestMapping("/gridBomItems")
	public void gridBomItems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			List<LogicProductionReturnItemDO> inList = new ArrayList<LogicProductionReturnItemDO>();
			LogicProductionGetDO proplan = logicProductionGetService.findListById(id);
			List<LogicProductionGetItemDO> planitem = logicProductionGetService.findGetItemList(proplan.getId());
			if(planitem!=null&&!planitem.isEmpty()&&planitem.size()>0){
				inList=this.planToReturn(planitem,proplan);
			}
			OutJsonGrid out = new OutJsonGrid(inList);
			out.printJSon(response);
		}
	}
	
	private List<LogicProductionReturnItemDO> planToReturn(List<LogicProductionGetItemDO> planitem,LogicProductionGetDO proplan) throws Exception{
		List<LogicProductionReturnItemDO> inList = new ArrayList<LogicProductionReturnItemDO>();
		List<LogicProductionReturnItemDO> inListy=this.listItem(proplan.getZd001GetCode(), proplan.getZd003PiCode());
		for(int i=0;i<planitem.size();i++){
			LogicProductionReturnItemDO inItem = new LogicProductionReturnItemDO();
			inItem.setZd002MaterialsCode(planitem.get(i).getZd002MaterialsCode());
			inItem.setZd021BomId(planitem.get(i).getZd021BomId());
			inItem.setZd022ProCode(planitem.get(i).getZd022ProCode());
			inItem.setZd023ProName(planitem.get(i).getZd023ProName());
			inItem.setZd002MaterialsId(planitem.get(i).getZd002MaterialsId());
			inItem.setZd002MaterialsName(planitem.get(i).getZd002MaterialsName());
			inItem.setZd003MaterialsSpec(planitem.get(i).getZd003MaterialsSpec());
			inItem.setZd004MaterialsModel(planitem.get(i).getZd004MaterialsModel());
			inItem.setZd006Unit(planitem.get(i).getZd006Unit());
			inItem.setZd009Price(planitem.get(i).getZd009Price());
			inItem.setZd015MaterialsDescription(planitem.get(i).getZd015MaterialsSize());
			inItem.setZd016MaterialsSize(planitem.get(i).getZd015MaterialsSize());
			inItem.setZd017MaterialsColor(planitem.get(i).getZd016MaterialsColor());
			inItem.setZd018MaterialsQuality(planitem.get(i).getZd017MaterialsQuality());
			inItem.setZd020DdQuanlity(planitem.get(i).getZd007Quantity());
			inItem.setZd019ReturnQuanlity(this.getProductionQuantity(inListy, planitem.get(i).getZd002MaterialsCode()));
			if(inItem.getZd019ReturnQuanlity().compareTo(new BigDecimal(0.0))==1){
				BigDecimal bg =MathUtil.mathUtil.subtract(planitem.get(i).getZd007Quantity(), inItem.getZd019ReturnQuanlity());
				inItem.setZd007Quantity(bg);
			}else{
				inItem.setZd007Quantity(planitem.get(i).getZd007Quantity());
			}
			inList.add(inItem);
		}
		return inList;
	}
	
	/**
	 * 查询当前已退料的原材料
	 */
	private List<LogicProductionReturnItemDO> listItem(String plan,String picode)
			throws Exception {
		List<LogicProductionReturnItemDO> list = new ArrayList<LogicProductionReturnItemDO>();
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		scs.addCondition("zd002OriCode", plan, SearchCondition.OP_EQUAL);
		scs.addCondition("zd003PiCode", picode, SearchCondition.OP_EQUAL);
		List<LogicProductionReturnDO> result = logicProductionReturnService.findListByExample(scs).getResults();
		if(result!=null&&!result.isEmpty()&&result.size()>0){
			for(int i=0;i<result.size();i++){
				List<LogicProductionReturnItemDO> dispatItem = logicProductionReturnService.findReturnItemList(result.get(i).getId());
				list.addAll(dispatItem);
			}
		}
		return list;
	}
	
	private BigDecimal getProductionQuantity(List<LogicProductionReturnItemDO> list,String mCode){
		BigDecimal big = new BigDecimal(0.0);
		if(list!=null&&!list.isEmpty()&&list.size()>0){
			for(int i=0;i<list.size();i++){
				if(list.get(i).getZd002MaterialsCode().equals(mCode)){
					big=MathUtil.mathUtil.addtract(big, list.get(i).getZd007Quantity());
				}
			}
		}
		return big;
	}
	
	@RequestMapping(value = "/updateState")
	@ResponseBody
	public Map<String,String> updateState(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		Map<String,String> map=new HashMap<String,String>();
		try{
			String ids = request.getParameter("rows");
			if(ids!=null&&!"".equals(ids)){
				LogicProductionReturnDO lot=logicProductionReturnService.findListById(ids);
				if(lot.getId()!=null){
					lot.setZd011BillStatus(BillStatusUtil.PRORETURN_STATUS_SIX);
					logicProductionReturnService.update(lot, SessionUtil.getUser(request));
					map.put("msg", "SUCCESS");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("msg", "ERROR");
		}
		return map;
	}
}
